import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { login } from '../services/user';
import { setAuthority, getUser } from '../utils/authority';
import { reloadAuthorized } from '../utils/Authorized';
import { getPageQuery } from '../utils/utils';

const localRoomId = 'wareRoomId';

export const cache = {
  user() {
    return getUser() || {};
  },
  warehouse() {
    const { warehouse = [] } = this.user();
    return warehouse;
  },
  wareRoomId() {
    const localCache = localStorage.getItem(localRoomId);
    if (localCache) return localCache;
    const warehouse = this.warehouse();
    const defaultId = warehouse.length ? warehouse[0].id : '';
    if (defaultId) {
      this.saveWareRoomId(defaultId);
    }
    return defaultId;
  },
  saveWareRoomId(id) {
    localStorage.setItem(localRoomId, id);
  },
};

export default {
  namespace: 'user',

  state: {
    data: cache.user(),
    wareRoomId: cache.wareRoomId(),
  },

  effects: {
    * login({ payload }, { call, put }) {
      const { data: { admin } } = yield call(login, payload); // 登陆用户信息
      admin.authority = ['isLogin'];

      yield put({
        type: 'changeLoginStatus',
        payload: {
          data: admin, // 用户信息
        },
      });
      reloadAuthorized(); // 重新设置路由权限
      const urlParams = new URL(window.location.href);
      const params = getPageQuery();
      let { redirect } = params;
      if (redirect) {
        const redirectUrlParams = new URL(redirect);
        if (redirectUrlParams.origin === urlParams.origin) {
          redirect = redirect.substr(urlParams.origin.length);
          if (redirect.startsWith('/#')) {
            redirect = redirect.substr(2);
          }
        } else {
          window.location.href = redirect;
          return;
        }
      }
      yield put(routerRedux.replace(redirect || '/'));
    },
    * logout(_, { put }) {
      localStorage.clear(); // 登出清空缓存
      yield put({
        type: 'changeLoginStatus',
        payload: {
          data: '', // 清空用户信息
        },
      });
      reloadAuthorized();
      yield put(
        routerRedux.push({
          pathname: '/login',
          search: stringify({
            redirect: '',
          }),
        }),
      );
    },
    * warehouseId({ payload }, { put }) {
      yield put({
        type: 'changeHouseId',
        payload,
      });
      yield put({
        type: 'wareLocation/list',
      });
      yield put({
        type: 'check/list',
      });
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      const { data } = payload;
      setAuthority(data); // 本地缓存用户信息
      return {
        ...state,
        data,
        wareRoomId: data ? cache.wareRoomId() : '',
      };
    },
    changeHouseId(state, { payload }) {
      cache.saveWareRoomId(payload);
      return {
        ...state,
        wareRoomId: payload,
      };
    },
  },
};
